package com.bjut.vendormgrsys.service.impl;

import com.bjut.vendormgrsys.model.domain.CompanyPO;
import com.bjut.vendormgrsys.model.repository.CompanyRepository;
import com.bjut.vendormgrsys.service.CompanyService;
import com.bjut.vendormgrsys.util.DateUtils;
import com.bjut.vendormgrsys.util.JsonUtils;
import com.bjut.vendormgrsys.web.dto.other.CompanyInfo;
import com.bjut.vendormgrsys.web.dto.other.ResultCompanyInfoData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;
import java.util.Optional;

@Service
public class CompanyServiceImpl implements CompanyService {

    @PersistenceContext
    private EntityManager entityManager;

    private final CompanyRepository repository;

    @Autowired
    public CompanyServiceImpl(CompanyRepository repository) {
        this.repository = repository;
    }

    @Override
    @Transactional
    public void saveCompanyInfo(String id, CompanyInfo body) {
        CompanyPO companyPO = null;
        boolean isPersist = true;
        if (StringUtils.hasLength(id)) {
            Optional<CompanyPO> byId = repository.findById(id);
            if (byId.isPresent()) {
                companyPO = byId.get();
                isPersist = false;
            }
        }
        if (companyPO == null) {
            companyPO = new CompanyPO();
        }
        companyPO.setContent(JsonUtils.toString(body.getContent()));
        companyPO.setLastUpdated(DateUtils.now());
        if (!isPersist) {
            entityManager.merge(companyPO);
        } else {
            entityManager.persist(companyPO);
        }
    }

    @Override
    public String findId() {
        String id = null;
        List<CompanyPO> all = repository.findAll();
        if (!all.isEmpty()) {
            CompanyPO companyPO = all.get(0);
            id = companyPO.getId();
        }
        return id;
    }

    @Override
    public ResultCompanyInfoData findById(String id) {
        ResultCompanyInfoData data = new ResultCompanyInfoData();
        if (!StringUtils.hasLength(id)) {
            return data;
        }
        Optional<CompanyPO> byId = repository.findById(id);
        if (byId.isPresent()) {
            CompanyPO companyPO = byId.get();
            String content = companyPO.getContent();
            Object o = JsonUtils.toBean(content, Object.class);
            data.setContent(o);
            data.setLastUpdate(companyPO.getLastUpdated());
        }
        return data;
    }
}
